package leetcode.code1391;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {
	// __0
	// 3___1
	// __2
	int[][] grid;
	int m, n;
	int[] e1, e2, f, tx, ty;

	public boolean hasValidPath(int[][] grid) {
		int no = grid[0][0];
		if (no == 5) {
			return false;
		}
		this.grid = grid;
		this.m = grid.length - 1;
		this.n = grid[0].length - 1;
		if (m == 0 && n == 0) {
			return true;
		}
		this.e1 = new int[] { 0, 1, 0, 2, 1, 0, 0 };
		this.e2 = new int[] { 0, 3, 2, 3, 2, 3, 1 };
		this.f = new int[] { 2, 3, 0, 1 };
		this.tx = new int[] { -1, 0, 1, 0 };
		this.ty = new int[] { 0, 1, 0, -1 };
		boolean[][] been = new boolean[m + 1][n + 1];
		been[0][0] = true;
		if (no == 1 || no == 6) {
			return this.f(0, 1, 1, been);
		}
		if (no == 2 || no == 3) {
			return this.f(1, 0, 2, been);
		}
		return this.f(0, 1, 1, been) || this.f(1, 0, 2, been);
	}

	private boolean f(int x, int y, int from, boolean[][] been) {
		if (x < 0 || x > m || y < 0 || y > n) {
			return false;
		}
		if (been[x][y]) {
			return false;
		}
		been[x][y] = true;
		int no = this.grid[x][y];
		if (x == m && y == n) {
			if (f[from] == e1[no] || f[from] == e2[no])
				return true;
			else
				return false;
		}
		if (f[from] == e1[no]) {
			int to = e2[no];
			return this.f(x + tx[to], y + ty[to], to, been);
		} else if (f[from] == e2[no]) {
			int to = e1[no];
			return this.f(x + tx[to], y + ty[to], to, been);
		}
		been[x][y] = false;
		return false;
	}

	@Override
	public void debug4() {
		H.compare(true, this.hasValidPath(H.str2array1("[[2,4,3],[6,5,2]]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
